package com.genymobile.scrcpy.five.connection;

import com.genymobile.scrcpy.five.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ConnectionServer extends Thread {
    private final ICallback mCallback;
    private final int mPort;
    private final String tag;
    public ConnectionServer(String name, int port, ICallback callback) {
        mPort = port;
        mCallback = callback;
        tag = ConnectionServer.class.getSimpleName() + "_" + name;
    }

    private class ReceiveClientDataThread extends Thread {
        private final Socket clientSocket;
        ReceiveClientDataThread(Socket client) {
            LogUtils.log(tag, "客户端已连接：" + client.getInetAddress());
            this.clientSocket = client;
        }

        @Override
        public void run() {
            try {
                InputStream in = clientSocket.getInputStream();

                byte[] buffer = new byte[ConnectionConfig.RECEIVE_BUFFER_SIZE];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    // 转为字符串（按实际读取长度）
                    String message = null;
                    message = new String(buffer, 0, bytesRead);
//                    LogUtils.log(TAG, "收到数据: " + message);
                    synchronized (ConnectionServer.this) {
                        mCallback.handleLine(message);
                    }
                }
            } catch (IOException ignored) {

            } finally {
                try {
                    clientSocket.close();
                } catch (IOException ignored) {}
            }
        }
    }

    @Override
    public void run() {
        try (ServerSocket serverSocket = new ServerSocket(mPort)) {
            LogUtils.log(tag, String.format("服务器 %s 启动，等待连接...", mPort));

            while (true) {
                // 等待客户端连接（阻塞）
                Socket clientSocket = serverSocket.accept();
                new ReceiveClientDataThread(clientSocket).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.log(tag, "服务器已退出");
        mCallback.onServerFinished();
    }

    public interface ICallback {
        void handleLine(String line);
        default void onServerFinished() {}
    }
}
